package com.wuwangfu.transfor;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.operators.AbstractStreamOperator;
import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
import org.apache.flink.streaming.api.operators.StreamMap;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;

/**
 * @Author jcshen
 * @Date 2023-02-22
 * @PackageName:com.wuwangfu.transfor
 * @ClassName: MapTransform
 * @Description:
 * @Version 1.0.0
 *
 * https://nightlies.apache.org/flink/flink-docs-release-1.14/docs/dev/datastream/operators/overview/#map
 */
public class MapTransf {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<Integer> nums = env.fromElements(1, 2, 3, 4, 5, 6, 7, 8, 9);

        SingleOutputStreamOperator<Integer> maped = nums.transform("MyMap", //名称
                TypeInformation.of(Integer.class),//输出类型
                //处理逻辑
                new StreamMap<>(new MapFunction<Integer, Integer>() {
                    @Override
                    public Integer map(Integer value) throws Exception {
                        return value * 2;
                    }
                }));

        //maped.print();

        SingleOutputStreamOperator<Integer> myMap = nums.transform("MyMap", //名称
                TypeInformation.of(Integer.class),//输出类型
                //自定义处理逻辑
                new MyStreamMap());

        myMap.print();

        env.execute();
    }


    /**
     * 自定义处理逻辑
     *
     * AbstractStreamOperator<Integer>
     *     Integer->输入类型
     *
     * OneInputStreamOperator<Integer,Integer>
     *     Integer->输入类型
     *     Integer->输出类型
     */
    private static class MyStreamMap extends AbstractStreamOperator<Integer> implements OneInputStreamOperator<Integer,Integer> {
        /**
         * 重写 processElement 方法
         *
         * @param element
         * @throws Exception
         */
        @Override
        public void processElement(StreamRecord<Integer> element) throws Exception {
            //获取数据
            Integer in = element.getValue();
            //处理数据
            Integer out = in * 2;
            //将要输出数据放入element中
            element.replace(out);
            //输出，通过 AbstractStreamOperator 的 output 方法输出
            output.collect(element);
        }
    }
}
